package com.yang.filter;

import com.yang.utils.JwtUtils;
import com.yang.service.UserService;
import com.yang.domain.User;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.ArrayList;

/**
 * 令牌校验过滤器
 */
@Slf4j
@Component
public class TokenFilter implements Filter {

    @Autowired
    private UserService userService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        // 检查token是否存在且格式正确
        if (token != null && token.startsWith("Bearer ")) {
            try {
                // 去除"Bearer "前缀，获取纯token信息
                token = token.substring(7);
                // 解析token获取用户名
                String username = JwtUtils.parseJWT(token);
                // 根据用户名查询用户信息获取用户ID
                User user = userService.selectUserByUsername(username);
                if (user != null) {
                    // 设置用户ID到请求属性中
                    request.setAttribute("userId", user.getUserId());
                }
                // 尝试获取角色码（如果token中包含）
                String roleCode = null;
                try {
                    roleCode = JwtUtils.parseRoleCode(token);
                } catch (Exception e) {
                    // 如果token中没有角色码，忽略异常
                    log.debug("Token中未包含角色码信息: {}", e.getMessage());
                }
                // 将用户名和角色码存储到请求属性中，供后续使用
                request.setAttribute("username", username);
                if (roleCode != null) {
                    request.setAttribute("roleCode", roleCode);
                }
                // 创建认证令牌对象，用于Spring Security进行用户认证
                UsernamePasswordAuthenticationToken authentication =
                        new UsernamePasswordAuthenticationToken(username, null, new ArrayList<>());
                // 将认证信息设置到SecurityContext中，完成用户认证
                SecurityContextHolder.getContext().setAuthentication(authentication);
            } catch (Exception e) {
                // token无效时，不设置认证信息，让Spring Security处理
                log.warn("Invalid JWT token: {}", e.getMessage());
            }
        }
        // 继续执行其他过滤器或请求的业务逻辑
        filterChain.doFilter(request, response);
    }
}
